using AutoMapper;
using MediatR;
using SqlSugar;
using TaskProject.Application.Command.Plan;
using TaskProject.Domain.Plan;
using TaskProject.ErrorCode;
using TaskProject.InfrasIntructure.Implement;
using TaskProject.Extension;

namespace TaskProject.Application.Handler.Plan
{
    /// <summary>
    /// 更新生产计划处理器
    /// </summary>
    public class UpdateProductionPlanHandler : IRequestHandler<UpdateProductionPlanCommand, APIResult<bool>>
    {
        private readonly DatabaseContext _db;
        private readonly IMapper _mapper;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public UpdateProductionPlanHandler(DatabaseContext db, IMapper mapper, IHttpContextAccessor httpContextAccessor)
        {
            _db = db;
            _mapper = mapper;
            _httpContextAccessor = httpContextAccessor;
        }

        public async Task<APIResult<bool>> Handle(UpdateProductionPlanCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<bool>();

            try
            {
                // 检查生产计划是否存在
                var existingPlan = await _db.sqlSugar.Queryable<ProductionPlanModel>()
                    .Where(p => p.PlanId == request.PlanId && !p.IsDel)
                    .FirstAsync(cancellationToken);

                if (existingPlan == null)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "生产计划不存在";
                    return result;
                }

                // 检查计划单号是否重复（排除当前记录）
                var duplicateOrderNumber = await _db.sqlSugar.Queryable<ProductionPlanModel>()
                    .Where(p => p.PlanOrderNumber == request.PlanOrderNumber && p.PlanId != request.PlanId && !p.IsDel)
                    .AnyAsync(cancellationToken);

                if (duplicateOrderNumber)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "计划单号已存在，请使用其他单号";
                    return result;
                }

                // 验证生产物品
                if (request.ProductionItems == null || !request.ProductionItems.Any())
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "请至少选择一个生产物品";
                    return result;
                }

                // 验证物品数量
                foreach (var item in request.ProductionItems)
                {
                    if (item.Quantity <= 0)
                    {
                        result.Code = APIEnum.Fail;
                        result.Msg = $"物品 {item.ItemName} 的数量必须大于0";
                        return result;
                    }
                }

                // 开始事务
                var resultFlag = await _db.sqlSugar.Ado.UseTranAsync(async () =>
                {
                    // 更新生产计划主表
                    await _db.sqlSugar.Updateable<ProductionPlanModel>()
                        .SetColumns(p => new ProductionPlanModel
                        {
                            PlanSubject = request.PlanSubject,
                            PlanOrderNumber = request.PlanOrderNumber,
                            DocumentDate = request.DocumentDate,
                            Remarks = request.Remarks,
                            SalesOrderNumber = request.SalesOrderNumber,
                            RelatedProjectName = request.RelatedProjectName,
                            PlanStatus = request.PlanStatus,
                            ExpectedStartDate = request.ExpectedStartDate,
                            ExpectedEndDate = request.ExpectedEndDate,
                            ProductionLine = request.ProductionLine,
                            Priority = request.Priority,
                            UpdateName = "系统用户", // 可以从当前登录用户获取
                            UpdateDate = DateTime.Now
                        })
                        .Where(p => p.PlanId == request.PlanId)
                        .ExecuteCommandAsync(cancellationToken);

                    // 删除原有的生产物品
                    await _db.sqlSugar.Deleteable<ProductionPlanItemModel>()
                        .Where(i => i.PlanId == request.PlanId)
                        .ExecuteCommandAsync(cancellationToken);

                    // 创建新的生产物品记录
                    var productionItems = new List<ProductionPlanItemModel>();
                    for (int i = 0; i < request.ProductionItems.Count; i++)
                    {
                        var item = request.ProductionItems[i];
                        var productionItem = _mapper.Map<ProductionPlanItemModel>(item);
                        // 不设置PlanItemId，让数据库自动生成
                        productionItem.PlanId = request.PlanId;
                        productionItem.PlannedQuantity = item.Quantity;
                        productionItem.CompletedQuantity = 0;
                        productionItem.SortOrder = item.SortOrder > 0 ? item.SortOrder : i + 1;
                        productionItems.Add(productionItem);
                    }

                    // 插入新的生产物品
                    if (productionItems.Any())
                    {
                        await _db.sqlSugar.Insertable(productionItems).ExecuteCommandAsync(cancellationToken);
                    }

                    // 删除原有的附件
                    await _db.sqlSugar.Deleteable<ProductionPlanAttachmentModel>()
                        .Where(a => a.PlanId == request.PlanId)
                        .ExecuteCommandAsync(cancellationToken);

                    // 创建新的附件记录
                    if (request.Attachments != null && request.Attachments.Any())
                    {
                        var attachments = new List<ProductionPlanAttachmentModel>();
                        foreach (var attachment in request.Attachments)
                        {
                            var attachmentModel = _mapper.Map<ProductionPlanAttachmentModel>(attachment);
                            attachmentModel.AttachmentId = await GetNextAttachmentIdAsync();
                            attachmentModel.PlanId = request.PlanId;
                            attachmentModel.UploadDate = DateTime.Now;
                            attachmentModel.UploadBy = "系统用户"; // 可以从当前登录用户获取
                            attachments.Add(attachmentModel);
                        }

                        // 插入新的附件
                        if (attachments.Any())
                        {
                            await _db.sqlSugar.Insertable(attachments).ExecuteCommandAsync(cancellationToken);
                        }
                    }

                    // 记录操作日志
                    var operationLog = new ProductionPlanOperationLogModel
                    {
                        LogId = await GetNextLogIdAsync(),
                        PlanId = request.PlanId,
                        OperationType = 2, // 编辑
                        OperationTypeName = "编辑",
                        OperationDescription = "更新生产计划信息",
                        BeforeStatus = existingPlan.PlanStatus,
                        AfterStatus = request.PlanStatus,
                        OperatorName = "系统用户", // 可以从当前登录用户获取
                        OperationTime = DateTime.Now,
                        IpAddress = _httpContextAccessor.HttpContext?.GetClientIpAddress() ?? "127.0.0.1",
                        Remarks = request.Remarks
                    };

                    await _db.sqlSugar.Insertable(operationLog).ExecuteCommandAsync(cancellationToken);

                    return true;
                });

                if (resultFlag.IsSuccess)
                {
                    result.Code = APIEnum.Success;
                    result.Msg = "生产计划更新成功";
                    result.Data = resultFlag.Data;
                }
                else
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = $"更新失败：{resultFlag.ErrorMessage}";
                }
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.Fail;
                result.Msg = $"更新失败：{ex.Message}";
            }

            return result;
        }



        /// <summary>
        /// 获取下一个附件ID
        /// </summary>
        private async Task<int> GetNextAttachmentIdAsync()
        {
            // 使用数据库函数获取下一个ID，避免并发冲突
            var nextId = await _db.sqlSugar.Ado.GetIntAsync("SELECT ISNULL(MAX(AttachmentId), 0) + 1 FROM ProductionPlanAttachmentModel");
            
            // 双重检查，确保ID唯一
            while (await _db.sqlSugar.Queryable<ProductionPlanAttachmentModel>().AnyAsync(p => p.AttachmentId == nextId))
            {
                nextId++;
            }
            
            return nextId;
        }

        /// <summary>
        /// 获取下一个日志ID
        /// </summary>
        private async Task<int> GetNextLogIdAsync()
        {
            // 使用数据库函数获取下一个ID，避免并发冲突
            var nextId = await _db.sqlSugar.Ado.GetIntAsync("SELECT ISNULL(MAX(LogId), 0) + 1 FROM ProductionPlanOperationLogModel");
            
            // 双重检查，确保ID唯一
            while (await _db.sqlSugar.Queryable<ProductionPlanOperationLogModel>().AnyAsync(p => p.LogId == nextId))
            {
                nextId++;
            }
            
            return nextId;
        }
    }
} 